<template>
    <a-row :gutter="7">
      <a-col :md="7" :sm="24">
        <a-card :bordered="false">
          <div style="background: #fff;padding-left:2px;height: 100%; margin-top: 0px">
            <a-row>
              <a-col :span="24">
                <j-dict-select-tag type="radio" v-model="treeSearchParam.levelType" dictCode="mdm_level_type" placeholder="单层BOM" />
              </a-col>
            </a-row>
            <a-row style="margin-top: 10px">
              <a-col :span="8">
                <j-search-select-tag v-model="treeSearchParam.materialTypeCode" dict="mdm_material_type,material_type_name,material_type_code"  />
              </a-col>
              <a-col :span="16">
                <a-input-search @search="onSearch" style="width:100%" placeholder="请输入物料描述信息"/>
              </a-col>
            </a-row>
            <a-spin :spinning="loading">
              <template v-if="treeData.length>0">
                <a-tree
                  class="mdm-bom-tree"
                  show-icon
                  showLine
                  :selectedKeys="selectedKeys"
                  @select="handleTreeSelect"
                  :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                  :treeData="treeData"
                  :autoExpandParent="autoExpandParent"
                  :expandedKeys="treeExpandedKeys"
                  @expand="handleTreeExpand"
                  style="margin-top: 5px">
                  <!-- 自定义子节点图标 -->
                  <a-icon slot="myIcon" type="unordered-list" style="color:#0c8fcf;"/>
                </a-tree>
              </template>
              <template v-else>
                <a-empty style="margin-top: 20px"/>
              </template>
            </a-spin>
          </div>
        </a-card>
      </a-col>
      <a-col :md="17" :sm="24">
        <a-card :bordered="false" title="BOM详情">
          <template v-if="!selectedDataIsEmpty">
<!--            <a-button @click="handleOk" slot="extra" type="primary" >保存</a-button>-->
            <j-form-container :disabled="true">
              <a-form-model ref="form" :model="selectedData" :rules="validatorRules" slot="detail">
                <a-row>
                  <a-col :span="8">
                    <a-form-model-item label="物料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialDesc">
                      <j-popup
                        v-model="selectedData.materialDesc"
                        field="materialDesc"
                        :org-fields="selectedData.superMaterialId ? 'material_id,material_code,material_desc,material_unit_code,material_type_id' : 'material_id,material_desc'"
                        :dest-fields="selectedData.superMaterialId ? 'materialId,materialCode,materialDesc,materialUnitCode,materialTypeId' : 'materialId,materialDesc'"
                        :code="selectedData.superMaterialId ? 'bom_detail_material_pop' : 'bom_main_material_pop'"
                        @input="infoPopupCallback" placeholder="请选择物料"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="工厂" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="factory">
                      <j-dict-select-tag type="list" v-model="selectedData.factory" dictCode="mdm_factory,factory_name,id" placeholder="请选择工厂" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="生效日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectiveDate">
                      <j-date placeholder="请选择生效日期" v-model="model.effectiveDate"  style="width: 100%" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :hidden="!model.superMaterialId">
                  <a-col :span="8" >
                    <a-form-model-item label="组件数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partQty">
                      <a-input-number v-model="selectedData.partQty" placeholder="请输入组件数量" style="width: 100%" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialUnitCode">
                      <j-search-select-tag type="list" v-model="model.materialUnitCode" dict="mdm_unit,unit_name,unit_code" placeholder="请选择单位" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="失效日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expiryDate">
                      <j-date placeholder="请选择失效日期" v-model="model.expiryDate"  style="width: 100%" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="损耗率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lossRate">
                      <a-input v-model="selectedData.lossRate" placeholder="请输入损耗率" ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="项目文本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectNote">
                      <a-input v-model="selectedData.projectNote" placeholder="请输入项目文本" ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden" >
                    <a-form-model-item label="仓储地点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageLocation">
                      <a-input v-model="selectedData.storageLocation" placeholder="请输入仓储地点" ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="BOM用途" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bomUseType">
                      <j-dict-select-tag type="list" v-model="selectedData.bomUseType" dictCode="mdm_use_type" placeholder="请选择BOM用途" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="消耗方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="consumeType">
                      <j-dict-select-tag type="list" v-model="selectedData.consumeType" dictCode="mdm_consume_type" placeholder="请选择消耗方式" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="版本编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="versionNum">
                      <a-input v-model="selectedData.versionNum" placeholder="请输入版本编号" ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" :hidden="colHidden">
                    <a-form-model-item label="工位编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="stationNum">
                      <a-input v-model="selectedData.stationNum" placeholder="请输入工位编号" ></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-form-model>
            </j-form-container>
            <a-row :hidden="!model.superMaterialId">
              <a-col :span="24" :style="{textAlign: 'right'}">
                <a :style="{ marginLeft: '8px', fontSize: '14px' }" @click="moreInfo">
                  更多信息 <a-icon :type="colHidden ? 'down' : 'up'" />
                </a>
              </a-col>
            </a-row>
            <a-tabs defaultActiveKey = "1">
              <a-tab-pane tab="子BOM列表" :key="refKeys[0]" :forceRender="true">
                <j-editable-table
                  :ref="refKeys[0]"
                  :columns="columns"
                  :dataSource="selectedDataChildren"
                  :maxHeight="300"
                  :rowNumber="true"
                  :rowSelection="false"
                  :actionButton="false"
                  :disabled="true"/>
              </a-tab-pane>
            </a-tabs>
          </template>
          <template v-else>
            <a-empty style="margin-top: 20px" description="请选择一个BOM记录"/>
          </template>
        </a-card>
      </a-col>
    </a-row>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import {getAction, httpAction} from "@api/manage";
  import {FormTypes} from "@/utils/JEditableTableUtil";
  import moment from "moment";

  export default {
    name: "MdmBomTree",
    mixins:[JeecgListMixin, JEditableTableModelMixin],
    components: {
    },
    data () {
      return {
        description: '物料BOM管理页面',
        loading: false,
        colHidden: true,
        treeData:[],
        myIcon:{slots: {icon: 'myIcon'}},
        selectedKeys: [],
        selectedData: {},
        model: {},
        selectedDataChildren: [],
        treeExpandedKeys: [],
        treeSearchParam: {
          materialTypeCode: 'FERT',
          levelType: '01',
          materialDesc: ''
        },
        autoExpandParent: true,
        refKeys: ['mdmBomDetail', ],
        // 表头
        columns: [
          {
            title: '物料ID',
            key: 'materialId',
            type: FormTypes.hidden,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '物料描述',
            key: 'materialDesc',
            type: FormTypes.popup,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
            popupCode: 'bom_detail_material_pop',
            orgFields: 'material_id,material_code,material_desc,material_unit_code,material_type_id',
            destFields: 'materialId,materialCode,materialDesc,materialUnitCode,materialTypeId',
            field: 'materialDesc',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '组件数量',
            key: 'partQty',
            type: FormTypes.inputNumber,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: 'BOM用量',
            key: 'sumQty',
            type: FormTypes.inputNumber,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'materialUnitCode',
            type: FormTypes.sel_search,
            dictCode:"mdm_unit,unit_name,unit_code",
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '损耗率',
            key: 'lossRate',
            type: FormTypes.input,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '项目文本',
            key: 'projectNote',
            type: FormTypes.input,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '仓储地点',
            key: 'storageLocation',
            type: FormTypes.input,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '用途',
            key: 'bomUseType',
            type: FormTypes.select,
            dictCode:"mdm_use_type",
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '消耗方式',
            key: 'consumeType',
            type: FormTypes.select,
            dictCode:"mdm_consume_type",
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '生效日期',
            key: 'effectiveDate',
            type: FormTypes.date,
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue: moment(new Date()).format('YYYY-MM-DD'),
          },
          {
            title: '失效日期',
            key: 'expiryDate',
            type: FormTypes.date,
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'9999-12-31',
          },
          {
            title: '版本编号',
            key: 'versionNum',
            type: FormTypes.input,
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '工位编号',
            key: 'stationNum',
            type: FormTypes.input,
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '物料编号',
            key: 'materialCode',
            type: FormTypes.hidden,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
        ],
        validatorRules: {
          materialDesc: [
            { required: true, message: '请选择物料!'},
          ],
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        url: {
          edit: "/mdm/bom/treeEdit",
          treeList: "/mdm/bom/treeList",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {

    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      selectedDataIsEmpty: function (){
        return Object.keys(this.selectedData).length === 0;
      },
    },
    methods: {
      loadData(){
        this.loadTree();
      },
      loadTree(){
        var that = this;
        that.treeData = [];
        that.selectedKeys = [];
        that.loading = true;
        getAction(this.url.treeList, this.treeSearchParam).then(res => {
          if (res.success && res.result ) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.treeData.push(temp)
            }
            this.setTreeIcon(that.treeData)

            this.selectedData = Object.assign({}, that.treeData[0]);
            this.model = this.selectedData;
            this.selectedKeys = [that.treeData[0].key]
            // 设置子级BOM列表
            this.selectedDataChildren = [];
            let children = that.treeData[0].children;
            if(children && children.length > 0){
              for(let i=0; i<children.length; i++){
                let child = Object.assign({}, children[i]);
                child.children = [];
                this.selectedDataChildren.push(child);
              }
            }
          }
        }).finally(() => {
          that.loading = false
        })
      },
      // 树被展开触发的事件
      handleTreeExpand(expandedKeys) {
        this.treeExpandedKeys = expandedKeys
      },
      // 树被选择触发的事件
      handleTreeSelect(selectedKeys, e) {
        let record = e.node.dataRef;
        this.selectedData = Object.assign({}, record);
        this.model = this.selectedData;
        this.selectedKeys = [record.key]
        // 设置子级BOM列表
        this.selectedDataChildren = [];
        let children = record.children;
        if(children && children.length > 0){
          for(let i=0; i<children.length; i++){
            let child = Object.assign({}, children[i]);
            child.children = [];
            this.selectedDataChildren.push(child);
          }
        }
      },
      setTreeExpandedKeys(node) {
        //只展开一级目录
        if (node.children && node.children.length > 0) {
          this.treeExpandedKeys.push(node.key)
          //下方代码放开注释则默认展开所有节点
          /**
           for (let a = 0; a < node.children.length; a++) {
            this.setTreeExpandedKeys(node.children[a])
          }
           */
        }
      },
      setTreeIcon(tData){
        if(tData && tData.length > 0){
          for(let i=0; i<tData.length; i++){
            let data = tData[i];
            Object.assign(data, this.myIcon);
            if(data.children && data.children.length > 0){
              this.setTreeIcon(data.children);
            }
          }
        }
      },
      onSearch(value){
        this.treeSearchParam.materialDesc = value || '';
        this.loadTree();
      },
      moreInfo(){
        this.colHidden = !this.colHidden;
      },
      infoPopupCallback(value,row){
        this.selectedData = Object.assign(this.selectedData, row);
        this.model = this.selectedData;
      },
      classifyIntoFormData(allValues) {
        return {
          ...this.model, // 展开
          children: allValues.tablesValue[0].values,
        }
      },
      /** 覆盖JEditableTable的方法，原基础上增加刷新树形 */
      request(formData) {
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }
        this.confirmLoading = true
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
          this.loadTree();
        })
      },
    }
  }
</script>
<style lang="less">
  /** 隐藏文件小图标 */
  .mdm-bom-tree.ant-tree {
    li span.ant-tree-switcher.ant-tree-switcher-noop {
      display: none;
    }
  }

</style>